import axios from "axios"
// import { useRouter } from 'vue-router';
import { useUserStore } from "@/store/user/index"
import { router } from "@/router/index"
import { ElMessage } from "element-plus"
const instance = axios.create({
    baseURL: "http://xue.cnkdl.cn:9082/mall-admin",
    timeout: 5000
})

instance.interceptors.request.use(config => {
    let token = localStorage.getItem("token")
    if (token) {
        config.headers = config.headers || {};
        config.headers["Authorization"] = token
    }
    return config
}, err => {
    return Promise.reject(err)
})

instance.interceptors.response.use(res => {
    const userStore = useUserStore()
    localStorage.getItem("token")
    if (res.data.code === 401) {
        // 返回login 页面
        router.push("/login")
        // 删除token
        localStorage.removeItem("token")
        // 删除pinia的数据 和动态路由
        userStore.activeMenus.forEach((item) => {
            router.removeRoute(item.name)
        })

        router.removeRoute("home")

        userStore.infoArr = []
        ElMessage.warning(res.data.message)
    }

    // if (res.data.code === 200 && ) {

    // }

    return res.data
}, err => {
    return Promise.reject(err)
})

export default instance